<?php

namespace api\mobile;

use think\facade\Db;
use app\common\model\Mobile;

/**
 * 52生活 [这家没跑了]
 */
class Ksbapp extends BaseModel
{
    private $goodsId = 47;
    private $header = [
        'Content-Type: application/json',
    ];

    /**
     * 创建订单
     *
     * @params
     * sub_order_id 系统订单号
     * amount 充值金额
     * mobile 充值号码
     * 
     * $return  false/供应商订单号
     */
    public function create($order)
    {
        // 下单之前，先查询是否已经有相同订单号的订单了，防止重复下单
        $query = $this->query($order['sub_order_id']);
        // 已经下过单了
        if (!empty($query['data']['external_order_id'])) {
            return $query['data']['external_order_id'];
        }

        $url = $this->info['url'] . '/api/export/commitOrder';
        $params = [
            'call_back_url' =>$this->notifyUrl,
            'goods_id' => $this->goodsId,
            'number_no' => strval($order['mobile']),
            'order_id' => $order['sub_order_id'],
            'time_stamp' => time(),
            'uid' => intval($this->info['app_id']),
        ];
        $params['sign'] = $this->getSign($params);
        $params['changer_price'] = $order['amount'];
        $res = curlPost($url, json_encode($params), $this->header, 5, true);
        $res = json_decode($res, true);

        $supplier_order_no = '';
        $remark = $res['msg'] ?? '下单失败';
        if (!isset($res['code'])) {
            $status = self::NEED_RETRY;
        } else if (in_array($res['code'], [1, 4005])) {
            $status = self::SUCCESS;
            $supplier_order_no = $res['data']['external_order_id'] ?? '';
        } else if ($res['code'] == 4007) {
            $status = self::LACK_OF_MONEY;
        } else {
            $status = self::FAIL;
        }

        return compact('status', 'supplier_order_no', 'remark');
    }

    /**
     * 查询余额
     * 
     * 单位：分
     */
    public function queryAmount()
    {
        $url = $this->info['url'] . '/api/export/queryAccount';
        $params = [
            'time_stamp' => time(),
            'uid' => intval($this->info['app_id']),
        ];
        $params['sign'] = $this->getSign($params);
        $res = curlPost($url, json_encode($params), $this->header);
        $res = json_decode($res, true);
        if (!isset($res['data']['balance'])) {
            $this->error = $res['msg'] ?? '查询频繁';
            return false;
        }
        return $res['data']['balance'];
    }

    /**
     * 订单查询
     */
    public function query($orderId)
    {
        $url = $this->info['url'] . '/api/export/queryOrder';
        $params = [
            'order_id' => $orderId,
            'time_stamp' => time(),
            'uid' => intval($this->info['app_id']),
        ];
        $params['sign'] = $this->getSign($params);
        $res = curlPost($url, json_encode($params), $this->header);
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * 生成签名
     */
    public function getSign($params)
    {
        if (isset($params['sign'])) {
            unset($params['sign']);
        }
        $str = '';
        foreach ($params as $k => $v) {
            $str .= $k . '^' . $v . '==';
        }
        $str .= $this->info['app_secret'];
        return strtolower(md5($str));
    }

    /**
     * 订单回调
     */
    public function notify($params)
    {
        $insert = [
            'sub_order_id' => $params['order_id'] ?? '',
            'params' => json_encode($params, JSON_UNESCAPED_UNICODE),
            'result' => 'OK'
        ];

        $fields = [
            'order_id', 'status', 'time_stamp',
        ];
        foreach ($fields as $field) {
            if (!isset($params[$field])) {
                $insert['result'] = '缺少参数【' . $field . '】';
                Db::name('mobile_notify')->insert($insert);
                return $insert['result'];
            }
        }

        $sign = $params['sign'] ?? '';
        $str = "order_id^{$params['order_id']}==status^{$params['status']}=={$this->info['app_secret']}==time_stamp^{$params['time_stamp']}";
        $checkSign = strtolower(md5($str));
        if ($sign !== $checkSign) {
            $insert['result'] = '验签失败';
            Db::name('mobile_notify')->insert($insert);
            return $insert['result'];
        }

        $order = Db::name('mobile_order')
            ->where('sub_order_id', $params['order_id'])
            ->where('mobile_supplier_id', $this->info['id'])
            ->find();
        if (empty($order)) {
            $insert['result'] = '订单不存在';
            Db::name('mobile_notify')->insert($insert);
            return $insert['result'];
        }

        if (in_array($order['supplier_status'], [3, 4, 99])) {
            // if ($order['supplier_status'] == 3) {
            $insert['result'] = '已经成功过';
            Db::name('mobile_notify')->insert($insert);
            return 'OK';
        }

        if ($order['supplier_status'] != 2) {
            $insert['result'] = '订单状态有误：' . $order['supplier_status'];
            Db::name('mobile_notify')->insert($insert);
            return $insert['result'];
        }

        // 供应商订单状态：1订单未创建 2订单已创建 3充值成功 4充值失败
        // 1成功 0失败
        $supplierStatusMap = [
            0 => 99, // 0失败 --> 99 充值失败，等待重试
            1 => 3, // 1已充值 --> 3充值成功
        ];
        $supplierStatus = $supplierStatusMap[$params['status']] ?? 2;
        if ($order['supplier_status'] == $supplierStatus) {
            Db::name('mobile_notify')->insert($insert);
            return 'OK';
        }
        $update = [
            'supplier_status' => $supplierStatus,
        ];
        if ($supplierStatus == 99) {
            // $update['refund_status'] = 2;   // 充值失败，退款
            $order['notify_url'] = '';  // 失败通知先不发
        }
        $update['finish_time'] = time();

        Db::name('mobile_notify')->insert($insert);

        Db::startTrans();
        try {
            // 如果是返佣模式，将订单结算方式改成待结算
            if ($supplierStatus == 3 && $order['settle_type'] == SETTLE_TYPE_PROFIT) {
                if ($order['profit'] == 0) {
                    $update['settle_status'] = 3;
                } elseif ($order['settle_status'] == 1) {
                    $update['settle_status'] = 2;
                }
            }

            Mobile::handleNotify($order, $update);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            $insert['result'] = '订单更新失败' . $order['id'] . '。' . $e->getMessage();
            Db::name('mobile_notify')->insert($insert);
            return $insert['result'];
        }

        return 'OK';
    }
}
